package pers.john.fsmanager.core;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class FileManager {
	private File base;
	public FileManager(String fileName) {
		base=new File(fileName);
	}
	public String ls() {
		StringBuilder sb=new StringBuilder();
		for(File file:base.listFiles()) {
			String prefix=file.isDirectory()?"d":"-";
			sb.append(prefix);
			sb.append("\t");
			sb.append(file.getName()+"\n");
		}
		return sb.toString();
	}
	public void copy(String source,String target) throws FileNotFoundException{
		File src=new File(base,source);
		if(!src.exists()) throw new FileNotFoundException();
		File tgt=new File(base,target);
		copy(src,tgt);
	}
	public void delete(String fn) throws FileNotFoundException{
		File target=new File(base,fn);
		if(!target.exists()) throw new FileNotFoundException();
		delete(target);
	}
	private  void copy(File source, File target) {
		if (!source.isDirectory()) {
			fileCopy(source, target);
		} else {
			target.mkdir();
			for(File file:source.listFiles()) {
				copy(file, new File(target,file.getName()));
			}
		}
	}

	private  void fileCopy(File source, File target) {
		InputStream in = null;
		OutputStream out = null;
		byte[] buf = new byte[1024];
		try {
			in = new FileInputStream(source);
			out = new FileOutputStream(target);
			int len=0;
			while((len=in.read(buf))!=-1) {
				out.write(buf,0,len);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				in.close();
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	private  void delete(File f) {
		if (f.isDirectory()) {
			for (File file : f.listFiles()) {
				delete(file);
			}
			f.delete();
		} else {
			f.delete();
		}
	}
	public static void main(String[] args) throws FileNotFoundException{
		FileManager fm=new FileManager("public");
//		String rs=fm.ls();
//		System.out.println(rs);
		//fm.copy("abc.txt", "abc1.txt");
		fm.delete("abc");
	}
}
